package com.example.peanutsubway.util;



import org.apache.commons.beanutils.ConvertUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 * @Author：liulei
 * @Version：1.0
 * @Date：2021/10/9-11:29
 * @Since:jdk1.8
 * @Description:
 */
public class ConvertEntity {

    /**
     * 将map集合封装为实体类对象
     *
     * @param parameterMap
     * @param tClass
     * @param <T>
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T> T convertEntityByData(Map<String, String[]> parameterMap, Class<T> tClass)  throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Set<String> keySet = parameterMap.keySet();
        T entity = tClass.newInstance();
        for (String key : keySet) { // key：请求参数的key值（表单元素的name值）
            boolean flag = flagField(key, tClass);
            if (flag) {
                Field declaredField = tClass.getDeclaredField(key);// 获取实体类中的成员变量
                String[] values = parameterMap.get(key);
                Object message = ConvertUtils.convert(values, String.class);
                declaredField.setAccessible(true);// 暴力破解
                declaredField.set(entity, ConvertUtils.convert(message, declaredField.getType()));
            }
        }
        return entity;
    }

    /**
     * 判断实体类中非存在成员变量
     *
     * @param fieldName
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> boolean flagField(String fieldName, Class<T> tClass) {
        Field[] declaredFields = tClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (declaredField.getName().equals(fieldName)) {
                return true;
            }
//            if (fieldName.contains(declaredField.getName())) {
//
//            }
        }
        return false;
    }
}
